package com.yangtzeu.jwc.business;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.utils.ACache;

public abstract class BaseParser {
    public static final int timeoutMillis = 20 * 1000;
    public String path;
    public Document doc;

    public BaseParser() {

    }

    public BaseParser(String path) {
	this.path = path;
    }

    public abstract BaseParser startParse(ParserListener listener,boolean fromCache);

    public Document parse(URL url) throws IOException {
	return Jsoup.parse(url, timeoutMillis);
    }

    public Document parse(String path, boolean fromCache) throws IOException {
	Document d = null;
	ACache ac = ACache.get(MyApplication.getInstance());
	if (fromCache) {
	    String docStr = ac.getAsString(path);
	    if (docStr == null) {
		d = parse(new URL(path));
		ac.put(path, d.toString());
	    } else {
		d = getDoc(docStr);
	    }
	} else {
	    d = parse(new URL(path));
	    ac.put(path, d.toString());
	}
	return d;
    }

    public Document getDoc(byte[] responseBody) {
	return getDoc(new String(responseBody));
    }

    public Document getDoc(String html) {
	return Jsoup.parse(html);
    }

    public static interface ParserListener {
	public void finish();

	public void failed();
    }
}
